package com.k.kpp.web.controller;

import com.k.kc.util.FileUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kivil
 */
@Controller
public class UploadDownloadController {
    private final static Logger LOGGER = LoggerFactory.getLogger(UploadDownloadController.class);

    @RequestMapping("/downloadToCsv")
    public void dlToCsv(HttpServletRequest request, HttpServletResponse response) {
        String param1 = request.getParameter("statData");
        LOGGER.info("request param:" + param1);
        try {
            String dlFileName = "CallTypeStatistics";
            response.reset();
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + dlFileName + ".csv" + "\"");
            // data
            List<Map<String, Object>> resultList = getTestData();
            // csv format
            StringBuilder sb = new StringBuilder();
            // title
            sb.append("createTime,type,value\r\n");
            // data
            resultList.forEach(itm -> {
                sb.append(itm.get("createTime")).append(",");
                sb.append(itm.get("type")).append(",");
                sb.append(itm.get("value")).append("\r\n");
            });
            response.getOutputStream().write(sb.toString().getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/downloadToExcel")
    public void dlToExcel(HttpServletResponse response) {
        Workbook wb = new XSSFWorkbook();
        setWorkBookData(wb, getTestData());
        String fileName = "test111.xlsx";
        try {
            response.setContentType("application/octet-stream;charset=iso8859-1");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/uploadFileWithForm")
    @ResponseBody
    public Map<String, Object> uploadFileWithForm(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(12);
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            String type = mRequest.getParameter("type");
            String remark = mRequest.getParameter("remark");
            LOGGER.info("request param type:{},remark:{}", type, remark);
            String saveDir = "";
            String saveFullPath = "";

            MultipartFile file = mRequest.getFile("file");
            if (file != null) {
                if (!checkFile(file)) {
                    result.put("msg", "check file failed file max size is 10M");
                    return result;
                }
                String saveFilename = FileUtils.formatFilename(file.getOriginalFilename());
                String uploadDir = "/home/upload/";
                saveDir = FileUtils.formatDir(uploadDir) + "suggest" + File.separator;
                LOGGER.info("saveDir:{},saveFilename:{}", saveDir, saveFilename);
                try {
                    saveFile(file, saveDir, saveFilename);
                } catch (Exception e) {
                    saveDir = "c:" + saveDir;
                    saveFile(file, saveDir, saveFilename);
                }
                saveFullPath = FileUtils.getFilePath(saveDir, saveFilename);
            }
            LOGGER.info("saveDir:{},saveFullPath:{}", saveDir, saveFullPath);
            result.put("msg", "success");
            return result;
        } catch (UnsupportedEncodingException e) {
            result.put("msg", "decode file name error");
            return result;
        } catch (IOException e) {
            LOGGER.error("suggest:error:upload file error:", e);
            result.put("msg", "upload file error");
            return result;
        } catch (Exception e) {
            LOGGER.error("suggest:error:runtime error:", e);
            result.put("msg", "runtime error");
            return result;
        }
    }

    private boolean checkFile(MultipartFile file) {
        return file != null && !file.isEmpty() && file.getSize() > 0 && file.getSize() <= 10 * 1024 * 1024;
    }

    private void saveFile(MultipartFile file, String saveDir, String saveName) throws IOException {
        String filePath = FileUtils.getFilePath(saveDir, saveName);
        File dirFile = new File(saveDir);
        if (!dirFile.exists()) {
            LOGGER.debug("Not found dir create dir");
            boolean isMkdirs = dirFile.mkdirs();
            if (!isMkdirs) {
                throw new IOException("dir not found create dir error:" + saveDir);
            }
        }
        file.transferTo(new File(filePath));
    }

    private List<Map<String, Object>> getTestData() {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("createTime", "2021-3-8 14:58:32");
            map.put("type", "1");
            map.put("value", i);
            list.add(map);
        }
        return list;
    }

    private void setWorkBookData(Workbook workBook, List<Map<String, Object>> data) {
        Sheet sheet = workBook.createSheet("sheet1");
        int rowCount = data.size() + 1;
        for (int i = 0; i < rowCount; i++) {
            Row rowData = sheet.createRow(i);
            if (i == 0) {
                rowData.createCell(0).setCellValue("title1");
                rowData.createCell(1).setCellValue("title2");
                rowData.createCell(2).setCellValue("title3");
            } else {
                Map<String, Object> itm = data.get(i - 1);
                rowData.createCell(0).setCellValue(String.valueOf(itm.get("createTime")));
                rowData.createCell(1).setCellValue(String.valueOf(itm.get("type")));
                rowData.createCell(2).setCellValue(String.valueOf(itm.get("value")));
            }
        }
    }

}
